<template>
    <div class="synchronize">
        <div class="synch-initing" v-if="!inited">
            <p v-if="error">
                <span v-text="error"></span>
                <button @click="getData()">Refresh</button>
                <button @click="$router.go(-1)">Go back</button>
            </p>
            <p v-else v-loading="true"></p>
        </div>

        <template v-else>

            <!-- 进度条 -->
            <div class="synch-steps" v-if="status.action == 'create'" :step="step">
                <p>
                    <strong :class="{pass: step>1, active:step == 1}"><i>1</i><em>Variants</em></strong>
                    <span :class="{active:step >= 2}"></span>
                    <strong :class="{pass: step>2, active:step == 2}"><i>2</i><em>Details</em></strong>
                    <span :class="{active:step >= 3}"></span>
                    <strong :class="{pass: step>3, active:step == 3}"><i>3</i><em>Pricing</em></strong>
                </p>
            </div>

            <!-- 主体区 -->
            <div class="synch-content">
                <!-- 选择变体 -->
                <SynchronizeIndex v-if="step == 1" />
                <!-- 内容详情 -->
                <SynchronizeDetail v-if="step == 2" />
                <!-- 价目表 -->
                <SynchronizePrice v-if="step == 3" />
            </div>

            <!-- 底部 -->
            <SynchronizeSave @save="doSave($event)" :disabled="disabled" />

        </template>

        <!-- 物流弹窗 -->
        <LogisticsComputedDialog />

        <!-- 离开对话框 -->
        <UxDialog :visible="!!dialog_leave" @close="dialog_leave && dialog_leave(false)">

            <div class="dialog-leave">
                <img src="@/assets/images/designer-leave.svg" alt="">
                <p>
                    <strong>Are you sure you want to leave the current page?</strong>
                    <span>Once leave,changes that you made may not be saved.</span>
                </p>
                <fieldset>
                    <button @click="dialog_leave && dialog_leave(true)">Leave</button>
                    <button @click="dialog_leave && dialog_leave(false)" type="primary">Stay</button>
                </fieldset>
            </div>

        </UxDialog>
    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "UserSynchronize",
    layout: "layout-logined",
    data () {
        return {
            inited: false,
            loading: false,
            error: "",
            cache: null,
            dialog_leave: null,
        };
    },
    computed: {
        ...mapState({
            currency: "currency",
            rate: "rate",
        }),
        ...mapState("synchronize", {
            clothes: "clothes",
            status: "status",
            setting: "setting",
            shop: "shop",
            mockups_cache: 'mockups_cache',
        }),
        ...mapGetters("synchronize", {
            request: "getRequest"
        }),
        step () {
            return (this.status || {}).step || 1;
        },
        // 是否禁用下一步
        disabled () {
            // 当草稿状态下重新保存时，还要判断是否有数据更新
            if (/detail|price/.test(this.status.action)) {
                return JSON.stringify(this.request) == this.cache;
            } else {
                return false;
            }
        },
    },

    watch: {
        currency () { this.resetVariants() },
    },
    methods: {

        async getData () {
            const option = {
                goods_id: parseInt(this.$route.query.goodsid) || 0, // 商店商品id
                temp_id: parseInt(this.$route.query.tempid) || 0, // 模板id
                shop_id: parseInt(this.$route.query.shopid) || 0, // 商店id
                action: this.$route.query.action || '',
            };

            // 初始化
            this.$store.dispatch("synchronize/init", option).then(res => {
                this.cache = JSON.stringify(this.request || {});
                this.inited = true;
            }).catch(error => {
                this.error = String(error) || "init fail";
                console.log(error)
            });
        },

        // 获取数据
        async getRequestFormat () {

            const option = this.request;
            const cache = this.mockups_cache
            const image_infos = option.image_infos || []

            const output_list = image_infos.map((item, index) => {

                const type = item.type == "size" ? "size" : index == 0 ? "main" : "normal"
                const product = this.clothes.find(p => p.design_id == item.design_id);
                const color = type != 'size' ? product.color_list.find(c => c.color_id == item.color_id) : null;
                const model = type != 'size' ? product.model_list.find(m => m.id == item.model_id) : null;

                const output = {
                    type: type,
                    product: product,
                    color: color || {},
                    model: model || {},
                    url: "",
                }

                if (output.type == 'size') {
                    // 没有数据不管
                    output.url = product.size_url
                } else {
                    const active = cache.find(i => i.type != 'size' && i.color_id == color.color_id && i.model_tag == model.model_tag && i.surface_name == model.surface_name)
                    output.url = active ? active.url : ''
                }
                return output;
            })


            // 有未生成的,生成模特图
            if (output_list.findIndex(i => i.type != 'size' && !i.url) >= 0) {

                const output_map = new Map();
                const drawer_list = output_list.filter(i => i.type != 'size' && !i.output).map((item, index) => {

                    const color = item.color;
                    const model = item.model;
                    output_map.set(index, item)

                    return {
                        color: this.$modelBackgroundColor(color.color_num, model) || '',
                        taxture: this.$modelColorTaxture(model, color),
                        model: model.model_url || '', // 模特图
                    }
                })


                const request = {
                    shop_id: this.shop.shop_id,
                    drawer_list: drawer_list,
                }
                const response = await this.$http("Drawer.batchDrawModelBackground", request);

                if (response.code === 0) {
                    const outputs = response.data || [];
                    outputs.map((item, index) => {
                        const active = output_map.get(index)
                        active && (active.url = item.result)
                    })
                } else {
                    return Promise.reject('Failed to generate image, please try again later')
                }

            }


            option.image_infos = output_list.map(item => ({
                type: item.type,
                spu: item.product.spu,
                design_id: item.product.design_id,
                color_id: (item.color || {}).color_id || '',
                surface_name: (item.model || {}).surface_name || '', // 模特展示面front|back
                model_tag: (item.model || {}).model_tag || 'hanging',
                url: item.url,
            }))

            return option

        },
        // 添加或保存草稿
        async putonDraft (option) {

            let response = null;

            if (this.status.action == 'create') {
                response = await this.$http("UserStore.setGoodPublishDraft", option);
            } else {
                response = await this.$http("UserStore.putGoodPublishDraft", option);
            }

            if (response && response.code === 0) {
                if (this.status.action == 'create') {
                    const data = response.data || {}
                    this.status.id = data.id;
                    option.id = data.id
                }
                return option;
            } else {
                return Promise.reject(response.msg || "Failed to save draft");
            }
        },

        // 上架
        async putonShelves (option) {

            if (option.id) {
                const response = await this.$http("UserStore.syncProduct", option.id);
                if (response.code === 0) {
                    // this.$uxMessage.success("Your product is being synced to " + name);
                    return option;
                } else {
                    return Promise.reject("Failed to sync product");
                }
            } else {
                return Promise.reject("Id does not exist!");
            }
        },


        // 保存事件,update|create|draft
        async doSave (type) {
            // 保存草稿
            // 保存并上架

            this.loading = this.$loading({ lock: true, text: "Loading..." });
            this.getRequestFormat().then(option => {
                return this.putonDraft(option)
            }).then(option => {
                if (type == 'draft') {
                    this.$uxMessage.success("Draft saved successfully");
                    return Promise.resolve(option)
                } else {
                    return this.putonShelves(option)
                }
            }).then(option => {
                // 完成跳转
                const action = this.status.action;

                this.loading && this.loading.close();
                this.loading = null;
                this.cache = null; // 清空缓存

                if (/detail|price/.test(this.status.action)) {
                    this.$router.go(-1);
                } else {
                    this.$router.push("/user/store?shop_id=" + this.shop.shop_id);
                }
            }).catch(error => {
                this.loading && this.loading.close();
                this.loading = null;
                this.$uxMessage.error(error);
            })

        },

        // 重置货币
        resetVariants () {
            if (this.setting.price_notify == 'change') {
                this.setting.currency = this.currency;
                this.setting.rate = this.rate;
                this.$store.commit("synchronize/SET_VARIANTS", this.clothes);
            }
        },

        // 缓存
        setCache () {
            this.cache = JSON.stringify(this.request || {});
        },

        // 是否可离开
        canLeave () {
            if (!this.cache) {
                // 缓存没有，则直接返回
                return true;
            } else if (JSON.stringify(this.request) == this.cache) {
                // 和缓存相同可离开
                return true;
            } else {
                return false;
            }
        },
    },

    created () {
        if (process.client) {

            this.getData();
            this.$on('global:beforeLogout', () => new Promise((res, rej) => {
                if (this.canLeave()) {
                    res(true)
                } else {
                    this.dialog_leave = (leave) => {
                        if (leave) {
                            this.dialog_leave = null;
                            window.onbeforeunload = null;
                            setTimeout(() => res(true), 10)
                        } else {
                            this.dialog_leave = null;
                            setTimeout(() => res(false), 10)
                        }
                    }
                }
            }))
            window.onbeforeunload = (event) => {
                let notify = "Changes that you made may not be saved.";
                if (this.canLeave()) {
                } else {
                    (event || window.event).returnValue = notify;
                    return notify;
                }
            };
        }
    },
    // 路由离开
    beforeRouteLeave (to, from, next) {
        if (this.canLeave()) {
            window.onbeforeunload = null;
            next();
        } else {
            next(false);
            this.dialog_leave = (leave) => {
                if (leave) {
                    this.dialog_leave = null;
                    window.onbeforeunload = null;
                    next()
                } else {
                    this.dialog_leave = null;
                }
            }

        }
    },
};
</script>
<style lang="scss" scoped>
.synchronize {
    display: flex;
    background: #fff;
    flex-direction: column;
    min-height: calc(100vh - 78px);
}

.synch-initing {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;

    p {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        position: relative;
        font-size: 16px;

        span {
            width: 100%;
            text-align: center;
            font-size: 16px;
            line-height: 20px;
        }

        button {
            width: 120px;
            height: 32px;
            margin: 32px 10px;
        }
    }
}

.synch-steps {
    height: 102px;
    margin: 0 -24px;
    background: #fafafa;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    border-bottom: 1px solid #ebebeb;

    p {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        max-width: 628px;
        padding-bottom: 26px;

        & > span {
            flex: 1;
            height: 4px;
            background: #c8c8c8;

            &.active {
                background: #ea4c89;
            }
        }

        strong {
            display: block;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            position: relative;
            i {
                display: block;
                width: 24px;
                height: 24px;
                line-height: 24px;
                text-align: center;
                font-size: 14px;
                color: #ffffff;
                background: #c8c8c8;
                border-radius: 24px;
            }
            em {
                position: absolute;
                left: 50%;
                top: 100%;
                margin-top: 10px;
                transform: translateX(-50%);
                height: 16px;
                font-size: 14px;
                color: #919191;
                line-height: 16px;
            }

            &.pass {
                i {
                    background-color: #ea4c89;
                }
                em {
                    color: #555;
                }
            }

            &.active {
                i {
                    background-color: #ea4c89;
                }
                em {
                    color: #ea4c89;
                }
            }
        }
    }

    ::v-deep .el-step__head {
        .el-step__line-inner {
            display: none;
        }
        &.is-success {
            .el-step__icon.is-text {
                background: #ea4c89;
                color: #ffffff;
            }
            .el-step__line {
                background: #ea4c89;
                height: 4px;
            }
        }
        &.is-process {
            .el-step__icon.is-text {
                width: 28px;
                height: 28px;
                background: #ea4c89;
                font-size: 16px;
                color: #ffffff;
                border: none;
            }
        }

        .el-step__icon.is-text {
            width: 28px;
            height: 28px;
            background: #c8c8c8;
            font-size: 16px;
            color: #ffffff;
            line-height: 28px;

            border: none;

            .el-step__icon-inner {
                font-weight: normal;
            }
        }
        .el-step__line {
            height: 4px;
            background-color: #c8c8c8;
        }
    }
    ::v-deep .el-step__main {
        margin-top: 14px;

        .el-step__title {
            height: 18px;
            font-size: 16px;
            color: #919191;
            line-height: 18px;
            font-weight: normal;
            &.is-process {
                color: #ea4c89;
            }
        }
        .el-step__description {
            display: none;
        }
    }
}

.synch-content {
    position: relative;
    box-sizing: border-box;
    max-width: 1140px;
    padding: 0 20px;
    margin: 0 auto;
    width: 100%;
}

.dialog-leave {
    width: 320px;
    height: 414px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 56px 14px 14px;

    img {
        width: 80px;
        height: 80px;
    }

    p {
        flex: 1;
        margin-top: 36px;
        display: flex;
        flex-direction: column;
        text-align: center;
        strong {
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 22px;
        }
        span {
            margin-top: 10px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 22px;
        }
    }

    fieldset {
        display: flex;
        flex-direction: column;
        width: 100%;

        button {
            height: 38px;
        }
        button + button {
            margin-top: 8px;
        }
    }
}
</style>
